<template>
  <div class="post-list">
    <div class="post-list-header">
      <h3 class="list-title">最新分享</h3>
      <div class="refresh-btn" @click="refreshPosts">
        <el-icon><Refresh /></el-icon>
      </div>
    </div>
    
    <div class="posts-container">
      <div 
        v-for="post in posts" 
        :key="post.id"
        class="post-item"
        @click="handlePostClick(post)"
      >
        <!-- 用户信息 -->
        <div class="post-header">
          <div class="user-info">
            <img :src="getUserAvatar(post)" :alt="post.userName || '匿名用户'" class="user-avatar" />
            <div class="user-details">
              <span class="user-name">{{ post.userName }}</span>
              <span class="post-time">{{ formatTime(post.createTime) }}</span>
            </div>
            <div v-if="post.isUserPost" class="user-post-badge">我的</div>
          </div>
          <div class="post-actions">
            <el-icon @click.stop="handleLike(post)" class="action-icon" :class="{ liked: post.isLiked }">
              <Star />
            </el-icon>
            <el-icon @click.stop="handleComment(post)" class="action-icon">
              <ChatLineRound />
            </el-icon>
            <!-- 暂时屏蔽分享功能 -->
            <!-- <el-icon @click.stop="handleShare(post)" class="action-icon">
              <Share />
            </el-icon> -->
          </div>
        </div>
        
        <!-- 帖子内容 -->
        <div class="post-content">
          <p class="post-text">{{ post.content }}</p>
          
          <!-- 话题标签 -->
          <div v-if="post.topics && post.topics.length > 0" class="post-topics">
            <span 
              v-for="topic in post.topics" 
              :key="topic"
              class="topic-tag"
            >
              #{{ topic }}
            </span>
          </div>
        </div>
        
        <!-- 图片展示 -->
        <div v-if="post.images && post.images.length > 0" class="post-images">
          <div 
            v-for="(image, index) in post.images" 
            :key="index"
            class="image-item"
            :class="getImageClass(post.images.length)"
            @click.stop="previewImage(image)"
          >
            <img :src="image" :alt="`图片${index + 1}`" class="post-image" />
            <div v-if="post.images.length > 9 && index === 8" class="more-images">
              +{{ post.images.length - 9 }}
            </div>
          </div>
        </div>
        
        <!-- 互动统计 -->
        <div class="post-stats">
          <span v-if="post.likeCount > 0" class="stat-item">
            <el-icon><Star /></el-icon>
            {{ post.likeCount }}
          </span>
          <span v-if="post.commentCount > 0" class="stat-item">
            <el-icon><ChatLineRound /></el-icon>
            {{ post.commentCount }}
          </span>
          <span v-if="post.shareCount > 0" class="stat-item">
            <el-icon><Share /></el-icon>
            {{ post.shareCount }}
          </span>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-if="posts.length === 0" class="empty-state">
        <img src="@/assets/imgs/search_null_data.png" alt="暂无数据" class="empty-image" />
        <p class="empty-text">暂无分享内容</p>
        <p class="empty-hint">快来分享你的生活吧！</p>
      </div>
    </div>
    
    <!-- 评论模态框 -->
    <CommentModal 
      :visible="showCommentModal" 
      :post="selectedPost"
      @close="handleCloseCommentModal"
    />
    
    <!-- 帖子详情模态框 -->
    <PostDetail 
      :visible="showPostDetail" 
      :postId="selectedPostId"
      @close="handleClosePostDetail"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Star, ChatLineRound, Share } from '@element-plus/icons-vue'
import { getPostsApi, getUserPostsApi, likePostApi, unlikePostApi, sharePostApi, addCommentApi } from '@/api/discover'
import { useUserStore } from '@/stores/user'
import CommentModal from './CommentModal.vue'
import PostDetail from './PostDetail.vue'

// 用户store
const userStore = useUserStore()

// 帖子数据
const posts = ref([])
const loading = ref(false)

// 当前用户ID
const currentUserId = computed(() => userStore.userInfo?.id)

// 获取用户头像
const getUserAvatar = (post) => {
  // 如果是当前用户的帖子，使用用户信息中的头像
  if (post.isUserPost && userStore.userInfo?.avatar) {
    return userStore.userInfo.avatar
  }
  // 否则使用帖子中的头像，如果没有则使用默认头像
  return post.userAvatar || '/src/assets/imgs/avatar_unlogin.png'
}

// 评论模态框状态
const showCommentModal = ref(false)
const selectedPost = ref({})

// 帖子详情模态框状态
const showPostDetail = ref(false)
const selectedPostId = ref(null)

// 处理帖子数据格式
const processPostData = (post) => ({
  id: post.id,
  content: post.content,
  images: post.images ? post.images.map(img => img.imageUrl || img) : [],
  topics: post.topics ? post.topics.map(topic => topic.topicName || topic) : [],
  userName: post.userName || '匿名用户',
  userAvatar: post.userAvatar || '/src/assets/imgs/avatar_unlogin.png',
  createTime: post.createdAt,
  likeCount: post.likeCount || 0,
  commentCount: post.commentCount || 0,
  shareCount: post.shareCount || 0,
  isLiked: post.isLiked || false,
  privacy: post.privacy,
  status: post.status
})

// 获取帖子列表
const getPosts = async () => {
  try {
    loading.value = true
    console.log('开始获取帖子列表...')
    
    let allPosts = []
    let userPosts = []
    
    // 获取所有帖子
    try {
      const response = await getPostsApi({ page: 1, limit: 10 })
      console.log('所有帖子API响应:', response)
      
      if (response && response.data && response.data.posts && Array.isArray(response.data.posts)) {
        allPosts = response.data.posts.map(processPostData)
        console.log('获取到所有帖子数量:', allPosts.length)
      } else if (response && Array.isArray(response)) {
        allPosts = response.map(processPostData)
        console.log('获取到所有帖子数量(数组格式):', allPosts.length)
      } else if (response && response.posts && Array.isArray(response.posts)) {
        allPosts = response.posts.map(processPostData)
        console.log('获取到所有帖子数量(response.posts):', allPosts.length)
      }
    } catch (error) {
      console.warn('获取所有帖子失败:', error)
    }
    
    // 如果用户已登录，获取当前用户的帖子
    if (currentUserId.value) {
      try {
        const userResponse = await getUserPostsApi(currentUserId.value, { page: 1, limit: 10 })
        console.log('用户帖子API响应:', userResponse)
        
        if (userResponse && userResponse.data && userResponse.data.posts && Array.isArray(userResponse.data.posts)) {
          userPosts = userResponse.data.posts.map(processPostData)
          console.log('获取到用户帖子数量:', userPosts.length)
        } else if (userResponse && Array.isArray(userResponse)) {
          userPosts = userResponse.map(processPostData)
          console.log('获取到用户帖子数量(数组格式):', userPosts.length)
        } else if (userResponse && userResponse.posts && Array.isArray(userResponse.posts)) {
          userPosts = userResponse.posts.map(processPostData)
          console.log('userPosts:', userPosts)
          console.log('获取到用户帖子数量(response.posts):', userPosts.length)
        }
      } catch (error) {
        console.warn('获取用户帖子失败:', error)
      }
    }
    
    // 合并帖子，去重（用户帖子优先显示）
    const postMap = new Map()
    
    // 先添加所有帖子
    allPosts.forEach(post => {
      postMap.set(post.id, post)
    })
    
    // 再添加用户帖子（会覆盖重复的）
    userPosts.forEach(post => {
      postMap.set(post.id, { ...post, isUserPost: true })
    })
    
    posts.value = Array.from(postMap.values())
    
    // 按创建时间排序（最新的在前）
    posts.value.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
    
    console.log('最终帖子数据:', posts.value)
    
    // 如果没有任何数据，使用模拟数据
    if (posts.value.length === 0) {
      console.log('没有获取到任何帖子数据，使用模拟数据')
      posts.value = [
        {
          id: 1,
          content: '今天搬到了新的合租公寓，环境真的很不错！室友们都很友好，期待在这里的美好生活 🏠✨',
          images: [
            '/src/assets/imgs/room_text_bg.png',
            '/src/assets/imgs/discover.png'
          ],
          topics: ['谷粒生活', '合租日常'],
          userName: '谷粒用户001',
          userAvatar: '/src/assets/imgs/avatar_login.png',
          createTime: new Date().toISOString(),
          likeCount: 12,
          commentCount: 5,
          shareCount: 2,
          isLiked: false,
          privacy: 'public',
          status: 'active',
          isUserPost: false
        },
        {
          id: 2,
          content: '分享一个超好用的生活小技巧，在冰箱里放一卷纸巾可以保持蔬菜新鲜！🥬',
          images: ['/src/assets/imgs/service_bg.png'],
          topics: ['好物推荐', '生活技巧'],
          userName: '生活达人',
          userAvatar: '/src/assets/imgs/my_people.png',
          createTime: new Date(Date.now() - 3600000).toISOString(),
          likeCount: 8,
          commentCount: 3,
          shareCount: 1,
          isLiked: true,
          privacy: 'public',
          status: 'active',
          isUserPost: false
        }
      ]
    }
    
  } catch (error) {
    console.error('获取帖子列表失败:', error)
    ElMessage.error('获取帖子列表失败')
    // 只有在API调用失败时才使用模拟数据
    posts.value = [
      {
        id: 1,
        content: '今天搬到了新的合租公寓，环境真的很不错！室友们都很友好，期待在这里的美好生活 🏠✨',
        images: [
          '/src/assets/imgs/room_text_bg.png',
          '/src/assets/imgs/discover.png'
        ],
        topics: ['谷粒生活', '合租日常'],
        userName: '谷粒用户001',
        userAvatar: '/src/assets/imgs/avatar_login.png',
        createTime: new Date().toISOString(),
        likeCount: 12,
        commentCount: 5,
        shareCount: 2,
        isLiked: false,
        privacy: 'public',
        status: 'active',
        isUserPost: false
      },
      {
        id: 2,
        content: '分享一个超好用的生活小技巧，在冰箱里放一卷纸巾可以保持蔬菜新鲜！🥬',
        images: ['/src/assets/imgs/service_bg.png'],
        topics: ['好物推荐', '生活技巧'],
        userName: '生活达人',
        userAvatar: '/src/assets/imgs/my_people.png',
        createTime: new Date(Date.now() - 3600000).toISOString(),
        likeCount: 8,
        commentCount: 3,
        shareCount: 1,
        isLiked: true,
        privacy: 'public',
        status: 'active',
        isUserPost: false
      }
    ]
  } finally {
    loading.value = false
  }
}

// 刷新帖子
const refreshPosts = () => {
  getPosts()
}

// 暴露方法给父组件
defineExpose({
  refreshPosts
})

// 格式化时间
const formatTime = (timeString) => {
  const time = new Date(timeString)
  const now = new Date()
  const diff = now - time
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return Math.floor(diff / 60000) + '分钟前'
  } else if (diff < 86400000) { // 1天内
    return Math.floor(diff / 3600000) + '小时前'
  } else {
    return Math.floor(diff / 86400000) + '天前'
  }
}

// 获取图片布局类名
const getImageClass = (count) => {
  if (count === 1) return 'single'
  if (count === 2) return 'double'
  if (count === 3) return 'triple'
  if (count === 4) return 'quad'
  return 'multiple'
}

// 预览图片
const previewImage = (imageUrl) => {
  // 这里可以实现图片预览功能
  ElMessage.info('图片预览功能开发中...')
}

// 点赞帖子
const handleLike = async (post) => {
  try {
    console.log('开始点赞操作，帖子ID:', post.id, '当前状态:', post.isLiked)
    
    if (post.isLiked) {
      // 取消点赞
      console.log('取消点赞...')
      const response = await unlikePostApi(post.id)
      console.log('取消点赞响应:', response)
      
      // 简化响应检查 - 只要没有错误就认为成功
      post.likeCount = Math.max(0, post.likeCount - 1)
      post.isLiked = false
      ElMessage.success('取消点赞')
    } else {
      // 点赞
      console.log('添加点赞...')
      const response = await likePostApi(post.id)
      console.log('点赞响应:', response)
      
      // 简化响应检查 - 只要没有错误就认为成功
      post.likeCount++
      post.isLiked = true
      ElMessage.success('点赞成功')
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 评论帖子
const handleComment = (post) => {
  selectedPost.value = post
  showCommentModal.value = true
}

// 关闭评论模态框
const handleCloseCommentModal = () => {
  showCommentModal.value = false
  selectedPost.value = {}
}

// 分享帖子
const handleShare = async (post) => {
  try {
    await sharePostApi(post.id)
    post.shareCount++
    ElMessage.success('分享成功')
  } catch (error) {
    console.error('分享失败:', error)
    ElMessage.error('分享失败，请重试')
  }
}

// 点击帖子
const handlePostClick = (post) => {
  selectedPostId.value = post.id
  showPostDetail.value = true
}

// 关闭帖子详情模态框
const handleClosePostDetail = () => {
  showPostDetail.value = false
  selectedPostId.value = null
}

onMounted(() => {
  getPosts()
})
</script>

<style scoped>
.post-list {
  padding: 0 16px 20px;
}

.post-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.list-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.refresh-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 50%;
  background-color: #f5f5f5;
  transition: all 0.3s ease;
}

.refresh-btn:hover {
  background-color: #e0e0e0;
  transform: rotate(180deg);
}

.posts-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.post-item {
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
}

.post-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #f0f0f0;
}

.user-details {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.user-post-badge {
  background-color: #4CAF50;
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 8px;
  margin-left: 8px;
  white-space: nowrap;
}

.user-name {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.post-time {
  font-size: 12px;
  color: #999;
}

.post-actions {
  display: flex;
  gap: 16px;
}

.action-icon {
  font-size: 18px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-icon:hover {
  color: #4CAF50;
  transform: scale(1.1);
}

.action-icon.liked {
  color: #e74c3c;
}

.post-content {
  margin-bottom: 12px;
}

.post-text {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
  margin: 0 0 8px 0;
}

.post-topics {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.topic-tag {
  padding: 2px 8px;
  background-color: #e8f5e8;
  color: #4CAF50;
  border-radius: 12px;
  font-size: 12px;
}

.post-images {
  margin-bottom: 12px;
}

.image-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.image-item:hover {
  transform: scale(1.02);
}

.post-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.more-images {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: bold;
}

/* 图片布局 */
.post-images {
  display: grid;
  gap: 4px;
}

.post-images .single {
  grid-column: 1;
  aspect-ratio: 16/9;
}

.post-images .double {
  grid-column: span 1;
  aspect-ratio: 1;
}

.post-images .triple {
  grid-column: span 1;
  aspect-ratio: 1;
}

.post-images .quad {
  grid-column: span 1;
  aspect-ratio: 1;
}

.post-images .multiple {
  grid-column: span 1;
  aspect-ratio: 1;
}

.post-images .double {
  grid-template-columns: 1fr 1fr;
}

.post-images .triple {
  grid-template-columns: 1fr 1fr 1fr;
}

.post-images .quad {
  grid-template-columns: 1fr 1fr;
}

.post-images .multiple {
  grid-template-columns: repeat(3, 1fr);
}

.post-stats {
  display: flex;
  gap: 16px;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.empty-image {
  width: 120px;
  height: 120px;
  opacity: 0.6;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 16px;
  color: #666;
  margin: 0 0 8px 0;
}

.empty-hint {
  font-size: 14px;
  color: #999;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .post-list {
    padding: 0 12px 16px;
  }
  
  .post-item {
    padding: 12px;
  }
  
  .user-avatar {
    width: 32px;
    height: 32px;
  }
  
  .user-name {
    font-size: 13px;
  }
  
  .post-time {
    font-size: 11px;
  }
  
  .post-text {
    font-size: 13px;
  }
  
  .action-icon {
    font-size: 16px;
  }
  
  .post-actions {
    gap: 12px;
  }
}
</style>
